/**
 * 回收站相关API接口
 * 基于后端API文档：我的模块API.md
 */

import type {
  BatchRestoreResponse,
  ClearRecycleBinResponse,
  DeleteItemResponse,
  ExpireStatus,
  GetRecycleBinResponse,
  PageParams,
  RecycleBinBatchRestoreReqVO,
  RecycleBinItem,
  RecycleBinItemType,
  RecycleBinPageRespVO,
  RestoreItemResponse,
} from '@/types/recycle-bin'
import { http } from '@/utils/request'

/**
 * 添加到回收站
 * POST /reading/recycle-bin/add
 */
export function addToRecycleBin(data: {
  itemType: RecycleBinItemType
  itemId: number
  deletedFrom?: string
  groupTitle?: string
}) {
  return http.post<{ code: number, message: string, data: boolean }>('/reading/recycle-bin/add', data)
}

/**
 * 获取回收站内容
 * GET /api/recycle-bin
 */
export function getRecycleBinContent(params: PageParams) {
  return http.get<GetRecycleBinResponse>('/reading/recycle-bin', params)
}

/**
 * 还原删除项
 * POST /api/recycle-bin/{itemId}/restore
 */
export function restoreItem(itemId: number) {
  return http.post<RestoreItemResponse>(`/reading/recycle-bin/${itemId}/restore`)
}

/**
 * 彻底删除项
 * DELETE /api/recycle-bin/{itemId}
 */
export function deleteItem(itemId: number) {
  return http.delete<DeleteItemResponse>(`/reading/recycle-bin/${itemId}`)
}

/**
 * 批量还原
 * POST /api/recycle-bin/batch-restore
 */
export function batchRestore(data: RecycleBinBatchRestoreReqVO) {
  return http.post<BatchRestoreResponse>('/reading/recycle-bin/batch-restore', data)
}

/**
 * 清空回收站
 * DELETE /api/recycle-bin/clear
 */
export function clearRecycleBin() {
  return http.delete<ClearRecycleBinResponse>('/reading/recycle-bin/clear')
}

/**
 * 批量删除（通过循环调用单个删除接口实现）
 */
export async function batchDelete(itemIds: number[]) {
  const deletePromises = itemIds.map(itemId => deleteItem(itemId))
  const responses = await Promise.all(deletePromises)

  // 检查所有删除是否成功 - 修正：后端返回的成功状态码是0，不是200
  const allSuccess = responses.every(response => response?.code === 0)

  return {
    code: allSuccess ? 0 : 500,
    msg: allSuccess ? '批量删除成功' : '部分删除失败',
    data: null,
  }
}

// ==================== 工具函数 ====================

/**
 * 计算过期状态
 */
export function getExpireStatus(expireAt: string): {
  status: ExpireStatus
  daysLeft: number
  text: string
  color: string
} {
  const now = new Date()
  const expireDate = new Date(expireAt)
  const diffMs = expireDate.getTime() - now.getTime()
  const daysLeft = Math.ceil(diffMs / (1000 * 60 * 60 * 24))

  if (daysLeft <= 0) {
    return {
      status: 'expired',
      daysLeft: 0,
      text: '已过期',
      color: '#f44336',
    }
  }
  else if (daysLeft <= 3) {
    return {
      status: 'warning',
      daysLeft,
      text: `${daysLeft}天后过期`,
      color: '#ff9800',
    }
  }
  else {
    return {
      status: 'normal',
      daysLeft,
      text: `${daysLeft}天后过期`,
      color: '#4caf50',
    }
  }
}

/**
 * 格式化删除时间
 */
export function formatDeleteTime(dateStr: string, options?: {
  showTime?: boolean
  relative?: boolean
}): string {
  const { showTime = true, relative = true } = options || {}

  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (relative) {
    if (diffDays === 0) {
      return showTime ? `今天 ${formatTime(date)}` : '今天'
    }
    else if (diffDays === 1) {
      return showTime ? `昨天 ${formatTime(date)}` : '昨天'
    }
    else if (diffDays < 7) {
      return showTime ? `${diffDays}天前 ${formatTime(date)}` : `${diffDays}天前`
    }
  }

  // 非相对时间格式
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  let result = `${year}-${month}-${day}`

  if (showTime) {
    result += ` ${formatTime(date)}`
  }

  return result
}

/**
 * 格式化时间
 */
function formatTime(date: Date): string {
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

/**
 * 获取回收站项目类型信息
 */
export function getRecycleBinTypeInfo(type: RecycleBinItemType) {
  const typeMap = {
    book_set: {
      label: '绘本集',
      icon: 'folder',
      color: '#4ecdc4',
    },
    book: {
      label: '绘本',
      icon: 'book',
      color: '#ff6b6b',
    },
    audio: {
      label: '音频',
      icon: 'sound',
      color: '#45b7d1',
    },
    reading_record: {
      label: '阅读记录',
      icon: 'time',
      color: '#ffa726',
    },
    favorite: {
      label: '收藏',
      icon: 'heart',
      color: '#e91e63',
    },
  }

  return typeMap[type] || typeMap.book
}

/**
 * 处理回收站项目封面URL
 */
export function processRecycleBinCover(coverUrl?: string): string {
  if (!coverUrl) {
    // 返回空字符串，让组件使用图标占位符
    return ''
  }

  // 如果是相对路径，添加基础URL
  if (!coverUrl.startsWith('http')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
    return `${baseUrl}${coverUrl}`
  }

  return coverUrl
}

/**
 * 生成回收站项目的唯一键
 */
export function getRecycleBinItemKey(item: RecycleBinItem): string {
  return `${item.itemType}_${item.itemId}_${item.id}`
}

/**
 * 按类型分组回收站项目
 */
export function groupRecycleBinItemsByType(items: RecycleBinItem[]): Record<RecycleBinItemType, RecycleBinItem[]> {
  const groups: Record<RecycleBinItemType, RecycleBinItem[]> = {
    book_set: [],
    book: [],
    audio: [],
    reading_record: [],
    favorite: [],
  }

  items.forEach((item) => {
    if (groups[item.itemType]) {
      groups[item.itemType].push(item)
    }
  })

  return groups
}

/**
 * 过滤回收站项目
 */
export function filterRecycleBinItems(
  items: RecycleBinItem[],
  filters: {
    keyword?: string
    type?: RecycleBinItemType
    expireStatus?: ExpireStatus
    dateRange?: [string, string]
  },
): RecycleBinItem[] {
  let filtered = [...items]

  // 关键词过滤
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    filtered = filtered.filter(item =>
      item.title.toLowerCase().includes(keyword)
      || item.groupTitle.toLowerCase().includes(keyword),
    )
  }

  // 类型过滤
  if (filters.type) {
    filtered = filtered.filter(item => item.itemType === filters.type)
  }

  // 过期状态过滤
  if (filters.expireStatus && filters.expireStatus !== 'normal') {
    filtered = filtered.filter((item) => {
      if (!item.expireAt)
        return false
      const { status } = getExpireStatus(item.expireAt)
      return status === filters.expireStatus
    })
  }

  // 日期范围过滤
  if (filters.dateRange) {
    const [startDate, endDate] = filters.dateRange
    filtered = filtered.filter((item) => {
      const itemDate = new Date(item.deletedAt).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime()
      return itemDate >= start && itemDate <= end
    })
  }

  return filtered
}

/**
 * 排序回收站项目
 */
export function sortRecycleBinItems(
  items: RecycleBinItem[],
  sortType: 'delete_time_desc' | 'delete_time_asc' | 'expire_time_asc' | 'type' | 'title_asc',
): RecycleBinItem[] {
  const sorted = [...items]

  switch (sortType) {
    case 'delete_time_desc':
      return sorted.sort((a, b) => new Date(b.deletedAt).getTime() - new Date(a.deletedAt).getTime())
    case 'delete_time_asc':
      return sorted.sort((a, b) => new Date(a.deletedAt).getTime() - new Date(b.deletedAt).getTime())
    case 'expire_time_asc':
      return sorted.sort((a, b) => {
        if (!a.expireAt && !b.expireAt)
          return 0
        if (!a.expireAt)
          return 1
        if (!b.expireAt)
          return -1
        return new Date(a.expireAt).getTime() - new Date(b.expireAt).getTime()
      })
    case 'type':
      return sorted.sort((a, b) => a.itemType.localeCompare(b.itemType))
    case 'title_asc':
      return sorted.sort((a, b) => a.title.localeCompare(b.title))
    default:
      return sorted
  }
}

/**
 * 计算回收站统计信息
 */
export function calculateRecycleBinStats(items: RecycleBinItem[]) {
  const stats = {
    total: items.length,
    byType: {} as Record<RecycleBinItemType, number>,
    expiring: 0,
    expired: 0,
  }

  // 初始化类型统计
  const types: RecycleBinItemType[] = ['book_set', 'book', 'audio', 'reading_record', 'favorite']
  types.forEach((type) => {
    stats.byType[type] = 0
  })

  // 统计各项数据
  items.forEach((item) => {
    // 类型统计
    if (stats.byType[item.itemType] !== undefined) {
      stats.byType[item.itemType]++
    }

    // 过期状态统计
    if (item.expireAt) {
      const { status } = getExpireStatus(item.expireAt)
      if (status === 'warning') {
        stats.expiring++
      }
      else if (status === 'expired') {
        stats.expired++
      }
    }
  })

  return stats
}

// ==================== 错误处理 ====================

/**
 * 处理回收站API错误
 */
export function handleRecycleBinError(error: any): string {
  const errorMessages: Record<number, string> = {
    50007: '回收站项目不存在',
    50008: '还原失败',
  }

  const code = error?.response?.data?.code || error?.code
  return errorMessages[code] || error?.message || '操作失败，请重试'
}

// ==================== 缓存相关 ====================

/**
 * 缓存键名
 */
export const CACHE_KEYS = {
  RECYCLE_BIN_CONTENT: 'recycle_bin_content',
  RECYCLE_BIN_STATS: 'recycle_bin_stats',
}

/**
 * 清除回收站相关缓存
 */
export function clearRecycleBinCache() {
  Object.values(CACHE_KEYS).forEach((key) => {
    uni.removeStorageSync(key)
  })
}

/**
 * 缓存回收站内容
 */
export function cacheRecycleBinContent(content: RecycleBinPageRespVO) {
  uni.setStorageSync(CACHE_KEYS.RECYCLE_BIN_CONTENT, content)
}

/**
 * 获取缓存的回收站内容
 */
export function getCachedRecycleBinContent(): RecycleBinPageRespVO | null {
  try {
    return uni.getStorageSync(CACHE_KEYS.RECYCLE_BIN_CONTENT) || null
  }
  catch {
    return null
  }
}
